package gui.reports.removed;

import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import reports.RemovedItemsReport;
import reports.Report;
import gui.common.*;

/**
 * Controller class for the removed items report view.
 */
public class RemovedReportController extends Controller implements IRemovedReportController
{
  private File timeFile  = new File("files/.removed_report_last_run");
  Date         sinceDate = new Date(timeFile.exists() ? timeFile.lastModified() : 0);

  /**
   * Constructor.
   * 
   * @param view
   *          Reference to the removed items report view
   */
  public RemovedReportController(IView view)
  {
    super(view);
    construct();
  }

  private boolean hasBeenRunBefore()
  {
    return sinceDate.getTime() != 0;
  }

  //
  // Controller overrides
  //

  /**
   * Returns a reference to the view for this controller.
   * 
   * {@pre None}
   * 
   * {@post Returns a reference to the view for this controller.}
   */
  @Override
  protected IRemovedReportView getView()
  {
    return (IRemovedReportView) super.getView();
  }

  /**
   * Sets the enable/disable state of all components in the controller's view. A component should
   * be enabled only if the user is currently allowed to interact with that component.
   * 
   * {@pre None}
   * 
   * {@post The enable/disable state of all components in the controller's view have been set
   * appropriately.}
   */
  @Override
  protected void enableComponents()
  {
    getView().enableSinceDate(true);
    getView().enableSinceLast(hasBeenRunBefore());

    if (getView().getSinceDate())
    {
      getView().enableSinceDateValue(true);
    }
    else if (getView().getSinceLast())
    {
      getView().enableSinceDateValue(false);
    }
  }

  /**
   * Loads data into the controller's view.
   * 
   * {@pre None}
   * 
   * {@post The controller has loaded data into its view}
   */
  @Override
  protected void loadValues()
  {
    if (hasBeenRunBefore())
    {
      getView().setSinceDate(false);
      getView().setSinceLast(true);
      getView().setSinceLastValue(sinceDate);
    }
    else
    {
      getView().setSinceDate(true);
      getView().setSinceDateValue(new Date());
      getView().enableSinceLast(false);
    }
  }

  //
  // IExpiredReportController overrides
  //

  /**
   * This method is called when any of the fields in the removed items report view is changed by
   * the user.
   */
  @Override
  public void valuesChanged()
  {
    enableComponents();
  }

  /**
   * This method is called when the user clicks the "OK" button in the removed items report view.
   */
  @Override
  public void display()
  {

    if (getView().getSinceDate())
    {
      sinceDate = getView().getSinceDateValue();
    }
    else
    {
      sinceDate = new Date(timeFile.lastModified());
    }

    final Report report = new RemovedItemsReport(sinceDate);

    report.generateReport(new ReportCallback(getView())
    {
      @Override
      public void success()
      {
        try
        {
          File file;

          if (getView().getFormat() == FileFormat.HTML)
          {
            file = report.toHtml();
          }
          else
          {
            file = report.toPdf();
          }

          // Create files directory if needed
          if (!timeFile.getParentFile().exists())
          {
            timeFile.getParentFile().mkdir();
          }

          // Updates the files lastModified time.
          FileOutputStream touch = new FileOutputStream(timeFile);
          touch.close();
          sinceDate.setTime(System.currentTimeMillis());

          Desktop.getDesktop().open(file);
        }
        catch (IOException e)
        {
          failure(e);
        }
      }

      @Override
      public void finished()
      {}
    });
  }
}
